<?php
namespace http;

class RequestResponse
{
    public $responseData = null;
    public $action = '';
    public $route = '';
    //路由
    public $routes = [
        '/'=>'jobs',
        '/jobs'=>'jobs',
        '/job/add'=>'add',
        '/job/edit'=>'edit',
        '/job/st'=>'st',
        '/job/del'=>'del',
        '/miss'=>'miss',
        '/wiki'=>'wiki',
    ];

    public function __construct()
    {
        $this->parseRoute();
    }

    public function parseRoute()
    {
        //把 ? 后面的去掉
        $s_uri = $_SERVER['REQUEST_URI'];
        if(false !== mb_strpos($s_uri, '?')){
            $s_uri = mb_substr($_SERVER['REQUEST_URI'], 0, mb_strpos($_SERVER['REQUEST_URI'], '?'));
        }
        $this->route = array_key_exists($s_uri, $this->routes) ? $s_uri : '/miss';
        $this->action = $this->routes[$this->route];
    }

    public function run()
    {
        $ctl = new JobController();
        if(method_exists($ctl, $this->action)){
            $this->responseData = call_user_func(array($ctl, $this->action));
        }else{
            $this->responseData = 'method 404';
        }
        return $this->response();
    }

    public function response()
    {
        if(is_string($this->responseData)){
            return $this->responseData;
        }
        if(is_array($this->responseData)){
            return json_encode($this->responseData);
        }
        return '404';
    }
}
